package flca.osm.perst.util;

import org.garret.perst.Storage;
import org.garret.perst.StorageFactory;

import flca.osm.PerstConstants;
import flca.osm.perst.model.PRootClass;

public class _PerstDbHelper implements PerstConstants
{
	private static _PerstDbHelper sInstance;

	public static _PerstDbHelper getInstance()
	{
		if (sInstance == null) {
			sInstance = new _PerstDbHelper();
		}
		return sInstance;
	}

	//-------------------------------------------------
	private Storage db;
	private PRootClass root;
	private String databaseName;
	
	private _PerstDbHelper()
	{
	}

	public void initialize(String aDatabaseName)
	{
		databaseName = aDatabaseName;
		
		if (db == null) {
			db = StorageFactory.getInstance().createStorage();
			db.open(getDbsName(), POOL_SIZE);
		}

		root = (PRootClass) db.getRoot(); // get storage root
		if (root == null) { 
            root = new PRootClass(db); // create root object
            db.setRoot(root); // register root object
        }

		db.beginThreadTransaction(Storage.SERIALIZABLE_TRANSACTION);
	}
	
	public PRootClass getRoot() {
		return root;
	}

	public void cleanup() 
	{
		try {
			if (db != null) {
				db.endThreadTransaction();
				db.close();
				System.out.println("done!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void commit() {
		db.endThreadTransaction();
		db.close();
		db.open(getDbsName(), POOL_SIZE);
		db.beginThreadTransaction(Storage.SERIALIZABLE_TRANSACTION);
	}

	//TODO via AppContext and properties files.
	private String getDbsName()
	{
		if (databaseName != null) {
			return databaseName;
		} else {
			throw new RuntimeException("Je moet databasenaam eerst zetten met in de initialize()!");
		}
	}
}
